<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :style="isWidth ? 'width:99%' : ''"
    class="tag-edit-dialog"
  >
    <div class="dialog-content">
      <!-- 头部区域 -->
      <div class="dialog-header">
        <div class="header-icon">
          <Icon icon="ep:price-tag" />
        </div>
        <div class="header-content">
          <h3 class="dialog-title">{{ dialogTitle }}</h3>
          <p class="dialog-subtitle">选择和管理标签</p>
        </div>
      </div>

      <!-- 标签选择区域 -->
      <div class="tag-selection-area">
        <div class="tag-groups">
          <div class="tag-group" v-for="item in listData" :key="item.id">
            <div class="group-header">
              <Icon icon="ep:folder" class="group-icon" />
              <span class="group-name">{{ item.name }}</span>
              <div class="group-count">
                <span class="count-text">{{ item.labelList.length }}个标签</span>
              </div>
            </div>

            <div class="tag-list">
              <el-check-tag
                v-for="tag in item.labelList"
                :key="tag.id"
                @click="setlabelList(tag)"
                :style="tag.checked ? { background: tag.bgColor, color: tag.textColor } : ''"
                class="tag-item"
              >
                <Icon icon="ep:price-tag" class="tag-icon" />
                <span class="tag-name">{{ tag.name }}</span>
                <Icon v-if="tag.checked" icon="ep:check" class="check-icon" />
              </el-check-tag>
            </div>
          </div>
        </div>

        <!-- 分隔线 -->
        <div class="divider">
          <div class="divider-line"></div>
          <div class="divider-text">
            <Icon icon="ep:arrow-down" class="divider-icon" />
            <span>已选标签</span>
          </div>
          <div class="divider-line"></div>
        </div>

        <!-- 已选标签区域 -->
        <div class="selected-tags-area">
          <div class="selected-header">
            <Icon icon="ep:collection-tag" class="selected-icon" />
            <span class="selected-title">当前标签</span>
            <div class="selected-count">
              <span class="count-badge">{{ formData.labelList.length }}</span>
            </div>
          </div>

          <div class="selected-tags">
            <div v-if="formData.labelList.length === 0" class="empty-state">
              <Icon icon="ep:price-tag" class="empty-icon" />
              <span class="empty-text">暂无选中标签</span>
            </div>

            <el-tag
              v-for="(init, index) in formData.labelList"
              :key="init.id"
              :style="{ background: init.bgColor, color: init.textColor }"
              closable
              @close="closeTags(init, index)"
              class="selected-tag"
            >
              <Icon icon="ep:price-tag" class="selected-tag-icon" />
              <span class="selected-tag-name">{{ init.name }}</span>
            </el-tag>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false" class="cancel-btn">
          <Icon icon="ep:close" class="btn-icon" />
          取消
        </el-button>
        <el-button @click="submitForm" type="primary" :disabled="formLoading" class="confirm-btn">
          <Icon icon="ep:check" class="btn-icon" />
          确定
        </el-button>
      </div>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import * as customerTagApi from '@/api/crm/customerTagConfig/index'
import * as CustomerApi from '@/api/crm/customer'

defineOptions({ name: 'EditTagFrom' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const props = defineProps({
  moduleId: {
    type: Number
  },
  isWidth: {
    type: Boolean,
    default: false
  }
})

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改

const formData = ref({
  customerId: undefined,
  labelList: []
})

/** 打开弹窗 */
const open = async (type: string, id?: number, labelList?: Array) => {
  dialogVisible.value = true
  formType.value = type
  if (type == 'search') {
    dialogTitle.value = '搜索标签'
    formData.value.labelList = JSON.parse(JSON.stringify(labelList))
    getTagList()
    return
  }
  if (type == 'create') {
    dialogTitle.value = '添加标签'
    formData.value.labelList = []
    formData.value.customerId = id
    getTagList()
    return
  }
  dialogTitle.value = t('action.' + type)
  resetForm()
  formData.value.customerId = id
  formData.value.labelList = JSON.parse(JSON.stringify(labelList))
  getTagList()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success', 'setlabelList']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 提交请求
  formLoading.value = true
  try {
    if (formType.value == 'search') {
      emit('setlabelList', formData.value.labelList)
      dialogVisible.value = false
      return
    }
    if (formType.value === 'update') {
      let obj = {
        customerId: formData.value.customerId,
        labelList: formData.value.labelList.map((item) => item.id)
      }
      await CustomerApi.updateCustomerTag(obj)
      message.success(t('common.updateSuccess'))
    }
    if (formType.value == 'create') {
      let obj = {
        customerIdList: formData.value.customerId,
        labelList: formData.value.labelList.map((item) => item.id)
      }
      await customerTagApi.batchCustomerUpdateLabel(obj)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    customerId: undefined,
    labelList: []
  }
}

const listData = ref([])
/** 标签查询列表 */
const getTagList = async () => {
  try {
    const data = await customerTagApi.getCustomerTagPage()
    let list = null
    if (props.moduleId) {
      list = data.list.filter((i) => i.moduleId == props.moduleId)
    } else {
      list = data.list
    }
    if (formData.value.labelList.length) {
      list.forEach((items) => {
        items.labelList.forEach((item) => {
          let check = formData.value.labelList.find((init) => init.id == item.id)
          if (check) {
            item.checked = true
          } else {
            item.checked = false
          }
        })
      })
    } else {
      list.forEach((items) => {
        items.labelList.forEach((item) => {
          item.checked = false
        })
      })
    }
    listData.value = list
  } finally {
  }
}
/*用户添加取消*/
const setlabelList = (tag) => {
  let tags = formData.value.labelList.find((item) => item.id == tag.id)
  if (tags) {
    listData.value.forEach((item) => {
      item.labelList.forEach((element) => {
        if (element.id == tag.id) {
          let indexs
          formData.value.labelList.forEach((its, index) => {
            if (its.id == tags.id) {
              indexs = index
            }
          })
          formData.value.labelList.splice(indexs, 1)
          element.checked = false
        }
      })
    })
  } else {
    listData.value.forEach((item) => {
      item.labelList.forEach((element) => {
        if (element.id == tag.id) {
          formData.value.labelList.push(element)
          element.checked = true
        }
      })
    })
  }
}
/*操作标签*/
const closeTags = (tag, index) => {
  listData.value.forEach((item) => {
    item.labelList.forEach((element) => {
      if (element.id == tag.id) {
        formData.value.labelList.splice(index, 1)
        element.checked = false
      }
    })
  })
}
</script>

<style lang="scss" scoped>
.tag-edit-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;
    overflow: hidden;

    @media (max-width: 768px) {
      width: 95% !important;
      margin: 20px auto;
      max-height: 90vh;
    }
  }

  :deep(.el-dialog__header) {
    display: none;
  }

  :deep(.el-dialog__body) {
    padding: 0;
    max-height: 70vh;
    overflow-y: auto;
  }

  :deep(.el-dialog__footer) {
    padding: 0;
    border-top: 1px solid #e5e7eb;
  }
}

.dialog-content {
  background: #f8fafc;
}

/* 对话框头部 */
.dialog-header {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px 24px;
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  color: white;
  border-radius: 10px;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;

  @media (max-width: 768px) {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
}

.header-content {
  flex: 1;
}

.dialog-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0 0 4px 0;

  @media (max-width: 768px) {
    font-size: 16px;
  }
}

.dialog-subtitle {
  font-size: 14px;
  opacity: 0.9;
  margin: 0;

  @media (max-width: 768px) {
    font-size: 12px;
  }
}

/* 标签选择区域 */
.tag-selection-area {
  padding: 24px;
  background: white;

  @media (max-width: 768px) {
    padding: 16px;
  }
}

.tag-groups {
  margin-bottom: 24px;
}

.tag-group {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;

  @media (max-width: 768px) {
    padding: 12px;
    margin-bottom: 16px;
  }
}

.group-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e5e7eb;
}

.group-icon {
  color: #0052cc;
  font-size: 16px;
}

.group-name {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  flex: 1;
}

.group-count {
  display: flex;
  align-items: center;
}

.count-text {
  font-size: 12px;
  color: #6b7280;
  background: #e5e7eb;
  padding: 2px 8px;
  border-radius: 12px;
}

.tag-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.tag-item {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 16px;
  border: 1px solid #d1d5db;
  background: white;
  color: #374151;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;

  &:hover {
    border-color: #0052cc;
    background: rgba(0, 82, 204, 0.05);
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(0, 82, 204, 0.15);
  }

  @media (max-width: 768px) {
    padding: 8px 12px;
    font-size: 13px;
  }
}

.tag-icon {
  font-size: 12px;
  color: inherit;
}

.tag-name {
  font-weight: 500;
}

.check-icon {
  font-size: 12px;
  color: inherit;
  margin-left: 4px;
}

/* 分隔线 */
.divider {
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 24px 0;

  @media (max-width: 768px) {
    margin: 20px 0;
  }
}

.divider-line {
  flex: 1;
  height: 1px;
  background: linear-gradient(90deg, transparent, #e5e7eb, transparent);
}

.divider-text {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  background: #f8fafc;
  border: 1px solid #e5e7eb;
  border-radius: 20px;
  font-size: 12px;
  color: #6b7280;
  font-weight: 500;
}

.divider-icon {
  font-size: 12px;
  color: #0052cc;
}

/* 已选标签区域 */
.selected-tags-area {
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e5e7eb;

  @media (max-width: 768px) {
    padding: 12px;
  }
}

.selected-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 12px;
}

.selected-icon {
  color: #0052cc;
  font-size: 16px;
}

.selected-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
  flex: 1;
}

.selected-count {
  display: flex;
  align-items: center;
}

.count-badge {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  color: white;
  font-size: 12px;
  font-weight: 600;
  padding: 2px 8px;
  border-radius: 12px;
  min-width: 20px;
  text-align: center;
}

.selected-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  min-height: 40px;
  align-items: flex-start;
  align-content: flex-start;
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  padding: 20px;
  color: #9ca3af;
  font-size: 14px;

  @media (max-width: 768px) {
    padding: 16px;
    font-size: 13px;
  }
}

.empty-icon {
  font-size: 20px;
  opacity: 0.5;
}

.empty-text {
  font-weight: 500;
}

.selected-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 16px;
  border: none;
  font-weight: 500;
  transition: all 0.2s ease;
  position: relative;

  &:hover {
    transform: scale(1.05);
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }

  @media (max-width: 768px) {
    padding: 8px 12px;
    font-size: 13px;
  }

  :deep(.el-tag__close) {
    margin-left: 6px;
    font-size: 12px;
    color: inherit;
    opacity: 0.8;
    transition: all 0.2s ease;

    &:hover {
      opacity: 1;
      transform: scale(1.2);
    }
  }
}

.selected-tag-icon {
  font-size: 12px;
  color: inherit;
}

.selected-tag-name {
  font-weight: 500;
}

/* 对话框底部 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px 24px;
  background: white;

  @media (max-width: 768px) {
    padding: 16px;
    flex-direction: column;
    gap: 8px;
  }
}

.cancel-btn {
  border: 2px solid #e5e7eb;
  color: #6b7280;
  background: white;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.2s ease;
  min-height: 40px;

  &:hover {
    border-color: #d1d5db;
    color: #374151;
  }

  @media (max-width: 768px) {
    width: 100%;
    order: 2;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

.confirm-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  color: white;
  transition: all 0.2s ease;
  min-height: 40px;

  &:hover {
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  }

  &:disabled {
    opacity: 0.6;
    cursor: not-allowed;
    transform: none;
    box-shadow: none;
  }

  @media (max-width: 768px) {
    width: 100%;
    order: 1;
  }

  .btn-icon {
    margin-right: 6px;
  }
}

/* 加载状态优化 */
:deep(.el-loading-mask) {
  border-radius: 8px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(4px);
}

:deep(.el-loading-spinner) {
  .circular {
    width: 32px;
    height: 32px;
  }
}

/* Element Plus 组件样式覆盖 */
:deep(.el-check-tag) {
  padding: 6px 12px;
  font-size: 12px;
  border-radius: 16px;
  transition: all 0.2s ease;

  @media (max-width: 768px) {
    padding: 8px 12px;
    font-size: 13px;
  }
}

:deep(.el-tag) {
  height: auto;
  line-height: 1.4;
  font-size: 12px;
  border: none;
  border-radius: 16px;
  padding: 6px 12px;

  @media (max-width: 768px) {
    padding: 8px 12px;
    font-size: 13px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .dialog-content {
    background: #1f2937;
  }

  .tag-selection-area {
    background: #374151;
  }

  .tag-group {
    background: #4b5563;
    border-color: #6b7280;
  }

  .group-name {
    color: #f9fafb;
  }

  .count-text {
    background: #6b7280;
    color: #f9fafb;
  }

  .tag-item {
    background: #374151;
    border-color: #6b7280;
    color: #f9fafb;

    &:hover {
      border-color: #60a5fa;
      background: rgba(96, 165, 250, 0.1);
    }
  }

  .divider-text {
    background: #4b5563;
    border-color: #6b7280;
    color: #d1d5db;
  }

  .selected-tags-area {
    background: #4b5563;
    border-color: #6b7280;
  }

  .selected-title {
    color: #f9fafb;
  }

  .empty-text {
    color: #9ca3af;
  }

  .dialog-footer {
    background: #374151;
  }

  :deep(.el-loading-mask) {
    background: rgba(55, 65, 81, 0.9);
  }
}

/* 高对比度模式适配 */
@media (prefers-contrast: high) {
  .tag-item {
    border: 2px solid #0052cc;

    &:hover {
      border-color: #1d4ed8;
      box-shadow: 0 0 0 2px rgba(0, 82, 204, 0.2);
    }
  }

  .selected-tag {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }

  .cancel-btn {
    border: 2px solid #6b7280;
  }

  .confirm-btn {
    background: #0052cc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
  }
}

/* 减少动画模式适配 */
@media (prefers-reduced-motion: reduce) {
  .tag-item,
  .selected-tag,
  .cancel-btn,
  .confirm-btn {
    transition: none;
  }

  .confirm-btn {
    &:hover {
      transform: none;
    }
  }

  .tag-item {
    &:hover {
      transform: none;
    }
  }

  .selected-tag {
    &:hover {
      transform: none;
    }
  }
}

/* 触摸设备优化 */
@media (hover: none) and (pointer: coarse) {
  .tag-item,
  .selected-tag {
    min-height: 44px;
    padding: 12px 16px;
  }

  .cancel-btn,
  .confirm-btn {
    min-height: 44px;
    padding: 12px 20px;
  }
}

/* 超小屏幕适配 */
@media (max-width: 480px) {
  .dialog-header {
    padding: 12px;
  }

  .tag-selection-area {
    padding: 12px;
  }

  .tag-group {
    padding: 8px;
  }

  .selected-tags-area {
    padding: 8px;
  }

  .dialog-footer {
    padding: 12px;
  }
}

/* 横屏模式适配 */
@media (max-width: 768px) and (orientation: landscape) {
  .dialog-header {
    padding: 12px 16px;
    flex-direction: row;
    text-align: left;
  }

  .tag-selection-area {
    padding: 16px;
  }

  .dialog-footer {
    flex-direction: row;
  }

  .cancel-btn,
  .confirm-btn {
    width: auto;
  }
}
</style>
